package com.int_tech.shebeiManager.controller;

import antlr.StringUtils;
import com.int_tech.data.dao.DataInfoDao;
import com.int_tech.data.entity.DataInfo;
import com.int_tech.shebeiManager.dao.*;
import com.int_tech.shebeiManager.entity.*;
import com.int_tech.utils.DateTool;
import com.int_tech.utils.HttpClient;
import com.int_tech.utils.KuaYu;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * Created by liubochao on 2018/6/16.
 */
@Controller
@RequestMapping("/shebei")
public class ShebeiController {

    @Autowired
    private DataInfoDao dataInfoDao;

    @Autowired
    private ShebeiDao shebeiDao;

    @Autowired
    private WenduDao wenduDao;

    @Autowired
    private ShiduDao shiduDao;

    @Autowired
    private ZhenDongXDao zhenDongXDao;

    @Autowired
    private ZhenDongYDao zhenDongYDao;

    @Autowired
    private ZhenDongZDao zhenDongZDao;

    @Autowired
    private ZuobiaoDao zuobiaoDao;

    @Autowired
    private YouliangDao youliangDao;
    /**
     * 检验并存储新设备编号
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void checkShebei() {

        //查询数据信息
        List<DataInfo> dataInfoList = dataInfoDao.findByStatus(0);

        //查询设备
//        List<Shebei> shebeis = shebeiDao.findAll();


        for (DataInfo dataInfo : dataInfoList) {
            Shebei shebei = shebeiDao.findByShebeiId(dataInfo.getShebeiId());

            if (shebei == null) {
                //新建
                shebei = new Shebei();
                shebei.setCreateTime(new Date());
                shebei.setShebeiId(dataInfo.getShebeiId());
                shebei.setStatus(0);

                shebei.setZfz("0");
                shebei.setYfz("0");
                shebei.setXfz("0");
                shebei.setShidufz("0");
                shebei.setWendufz("0");


                shebeiDao.save(shebei);
            }

            dataInfo.setStatus(1);

            dataInfoDao.save(dataInfo);
        }
    }

    /**
     * 定时获取设备列表
     * @param shebeiIdList
     * @param request
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    @ResponseBody
    @RequestMapping(value = "/getShebeiListOnTime", method = RequestMethod.POST, produces = "application/json")
    public String getShebeiListOnTime(String shebeiIdList,String shebeiId,HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

        KuaYu.kuaYuResponse(response);

        Sort sort = new Sort(Sort.Direction.ASC,"shebeiName");

        List<Shebei> shebeiList = shebeiDao.findAll(sort);

        String html = "";

        for(Shebei shebei : shebeiList)
        {
            String selectSheBei = shebeiId.equals(shebei.getShebeiId())?"cli_Two":"";
            if("A3001002003006007223344558".equals(shebei.getShebeiId()))
            {
                System.out.print(111);
            }
            String shebeiName = shebei.getShebeiName();

            if(shebeiIdList.contains(shebei.getShebeiId()))
            {
                if(org.apache.commons.lang.StringUtils.isEmpty(shebeiName))
                {
                    shebeiName = shebei.getShebeiId().substring(shebei.getShebeiId().length()-8,shebei.getShebeiId().length());
                }
                //查看停机状态A3
                List<DataInfo> dataInfos = dataInfoDao.findOneByShebeiIdAndZhenTouOrderByCreateTimeDesc(shebei.getShebeiId(),"A4");

                List<DataInfo> dataInfos2 = dataInfoDao.findOneByShebeiIdAndZhenTouOrderByCreateTimeDesc(shebei.getShebeiId(),"A3");

                if(dataInfos == null || dataInfos.size() == 0)
                {
                    dataInfos = dataInfos2;
                }
                else
                {
                    dataInfos.addAll(dataInfos2);
                }

                DataInfo dataInfo = new DataInfo();

                if(dataInfos == null || dataInfos.size() == 0)
                {
                    dataInfo = null;
                }
                else
                {
                    dataInfo = dataInfos.get(0);
                }

                if(dataInfo == null)
                {
                    html += "<li class='tab_Box_L_R_Child "+selectSheBei+"' name='"+shebei.getShebeiId()+"' style='color:red;'>" + shebeiName + "(离线)</li>";
                }
                else
                {
                    String A3Time = DateTool.Date2String(dataInfo.getCreateTime(),"yyyy-MM-dd");

                    String now = DateTool.Date2String(new Date(),"yyyy-MM-dd");

                    if(now.equals(A3Time))
                    {
                        html += "<li class='tab_Box_L_R_Child "+selectSheBei+"' name='"+shebei.getShebeiId()+"'>" + shebeiName + "</li>";
                    }
                    else
                    {
                        html += "<li class='tab_Box_L_R_Child "+selectSheBei+"' name='"+shebei.getShebeiId()+"' style='color:red;'>" + shebeiName + "(离线)</li>";
                    }
                }
            }


        }

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("pageHtml", html);

        return jsonObject.toString();
    }


    /**
     * 获取设备列表
     *
     * @param request
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    @ResponseBody
    @RequestMapping(value = "/getShebeiList", method = RequestMethod.POST, produces = "application/json")
    public String getShebeiList(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

        KuaYu.kuaYuResponse(response);

        Sort sort = new Sort(Sort.Direction.ASC,"shebeiName");

        List<Shebei> shebeiList = shebeiDao.findAll(sort);

        String html = "";

        for (Shebei shebei : shebeiList) {

            String shebeiName = shebei.getShebeiName();

            if(org.apache.commons.lang.StringUtils.isEmpty(shebeiName))
            {
                shebeiName = shebei.getShebeiId().substring(shebei.getShebeiId().length()-8,shebei.getShebeiId().length());
            }
            //查看停机状态A3
            List<DataInfo> dataInfos = dataInfoDao.findOneByShebeiIdAndZhenTouOrderByCreateTimeDesc(shebei.getShebeiId(),"A3");

            DataInfo dataInfo = new DataInfo();

            if(dataInfos == null || dataInfos.size() == 0)
            {
                dataInfo = null;
            }
            else
            {
                dataInfo = dataInfos.get(0);
            }



            if(dataInfo == null)
            {
                html += "<li class='tab_Box_L_R_Child' name='"+shebei.getShebeiId()+"' style='color:red;'>" + shebeiName + "(离线)</li>";
            }
            else
            {
                String A3Time = DateTool.Date2String(dataInfo.getCreateTime(),"yyyy-MM-dd");

                String now = DateTool.Date2String(new Date(),"yyyy-MM-dd");

                if(now.equals(A3Time))
                {
                    html += "<li class='tab_Box_L_R_Child' name='"+shebei.getShebeiId()+"'>" + shebeiName + "</li>";
                }
                else
                {
                    html += "<li class='tab_Box_L_R_Child' name='"+shebei.getShebeiId()+"' style='color:red;'>" + shebeiName + "(离线)</li>";
                }
            }
        }

        JSONObject jsonObject = new JSONObject();


        jsonObject.put("pageHtml", html);


        return jsonObject.toString();

    }


    /**
     * 修改设备信息
     * @param request
     * @param response
     * @param shebeiId
     * @param shebeiName
     * @param wendufz
     * @param shidufz
     * @param xfz
     * @param yfz
     * @param zfz
     * @return
     * @throws UnsupportedEncodingException
     */
    @ResponseBody
    @RequestMapping(value = "/updateShebei", method = RequestMethod.POST, produces = "application/json")
    public String updateShebei(HttpServletRequest request, HttpServletResponse response,String shebeiId,String shebeiName,String wendufz,String shidufz,String xfz,String yfz,String zfz) throws UnsupportedEncodingException {

        KuaYu.kuaYuResponse(response);

        Shebei shebei = shebeiDao.findByShebeiId(shebeiId);

        if(shebei == null)
        {
            shebei = new Shebei();
            shebei.setStatus(0);
            shebei.setCreateTime(new Date());
            shebei.setShebeiId(shebeiId);
        }
//        shebei.setStatus(0);
        shebei.setShebeiName(shebeiName);
        shebei.setUpdateTime(new Date());
        shebei.setWendufz(wendufz);
        shebei.setShidufz(shidufz);
        shebei.setXfz(xfz);
        shebei.setYfz(yfz);
        shebei.setZfz(zfz);

        shebeiDao.save(shebei);
        JSONObject jsonObject = new JSONObject();

        jsonObject.put("status","success");
        return jsonObject.toString();
    }


    /**
     * 获取温度
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void checkWendu() {

        //查询数据信息
        List<DataInfo> dataInfoList = dataInfoDao.findByStatus(1);

        for (DataInfo dataInfo : dataInfoList) {
            try {
                if("A1".equals(dataInfo.getZhenTou()))
                {

                    String s1 = dataInfo.getDataString();
                    //湿度
                    String wendu = s1.substring(126,128) + s1.substring(124,126);

                    wendu = String.valueOf((Integer.parseInt(wendu,16)*0.00268127)-46.85);

                    wendu = wendu.substring(0,wendu.lastIndexOf(".")+3);

                    Wendu wendu1 = new Wendu();

                    wendu1.setCreateTime(dataInfo.getCreateTime());
                    wendu1.setShebeiId(dataInfo.getShebeiId());
                    wendu1.setStatus(0);
                    wendu1.setWendu(wendu);

                    wenduDao.save(wendu1);

                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }


            dataInfo.setStatus(2);

            dataInfoDao.save(dataInfo);
        }
    }


    /**
     * 获取湿度
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void checkShidu() {

        //查询数据信息
        List<DataInfo> dataInfoList = dataInfoDao.findByStatus(2);

        for (DataInfo dataInfo : dataInfoList) {
            try {
                if("A1".equals(dataInfo.getZhenTou()))
                {

                    String s1 = dataInfo.getDataString();
                    //湿度
                    String shidu = s1.substring(130,132) + s1.substring(128,130);

                    shidu = String.valueOf((Integer.parseInt(shidu,16)*0.00190735)-6);

                    shidu = shidu.substring(0,shidu.lastIndexOf(".")+2);

                    Shidu shidu1 = new Shidu();

                    shidu1.setCreateTime(dataInfo.getCreateTime());
                    shidu1.setShebeiId(dataInfo.getShebeiId());
                    shidu1.setStatus(0);
                    shidu1.setShidu(shidu);

                    shiduDao.save(shidu1);

                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }


            dataInfo.setStatus(3);

            dataInfoDao.save(dataInfo);
        }
    }


    /**
     * 获取坐标
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void checkZuobiao() {

        //查询数据信息
        List<DataInfo> dataInfoList = dataInfoDao.findByStatus(3);

        for (DataInfo dataInfo : dataInfoList) {
            try {
                if("A1".equals(dataInfo.getZhenTou()))
                {

                    String s1 = dataInfo.getDataString();
                    //纬度
                    String lng = s1.substring(62,82);
                    String lngNew = "";

                    for(int i = 0 ;i < lng.length(); i++)
                    {
                        if(i%2 == 0)
                        {

                        }
                        else
                        {
                            lngNew += lng.substring(i,i+1);
                        }
                    }

                    lngNew = lngNew.replace("E",".");


                    //经度
                    String lat = s1.substring(82,104);

                    String latNew = "";

                    for(int i = 0 ;i < lat.length(); i++)
                    {
                        if(i%2 == 0)
                        {

                        }
                        else
                        {
                            latNew += lat.substring(i,i+1);
                        }
                    }

                    latNew = latNew.replace("E",".");


                    Zuobiao zuobiao = new Zuobiao();

                    zuobiao.setCreateTime(dataInfo.getCreateTime());
                    zuobiao.setShebeiId(dataInfo.getShebeiId());
                    zuobiao.setStatus(0);
                    zuobiao.setLat(latNew);
                    zuobiao.setLng(lngNew);

                    zuobiaoDao.save(zuobiao);

                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }


            dataInfo.setStatus(4);

            dataInfoDao.save(dataInfo);
        }
    }

    /**
     * 获取x
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void checkX() {

        //查询数据信息
        List<DataInfo> dataInfoList = dataInfoDao.findByStatus(4);

        for (DataInfo dataInfo : dataInfoList) {
            try {
                if("A1".equals(dataInfo.getZhenTou()))
                {

                    String s1 = dataInfo.getDataString();

                    String start = s1.substring(134,136);

                    if(start.startsWith("0")||start.startsWith("A"))
                    {
                        //振动
                        String x = s1.substring(134,136) + s1.substring(132,134);

                        Integer x1 = Integer.parseInt(x,16);

                        x = String.valueOf(x1*3.9);

                        ZhendongX zhendongX = new ZhendongX();

                        zhendongX.setCreateTime(dataInfo.getCreateTime());
                        zhendongX.setShebeiId(dataInfo.getShebeiId());
                        zhendongX.setStatus(0);
                        zhendongX.setX(x);

                        zhenDongXDao.save(zhendongX);
                    }
                    else
                    {

//                       //振动
                        String x = s1.substring(134,136) + s1.substring(132,134);

//                        Integer x1 = Integer.parseInt(x,16);

                        Integer x1 = Integer.parseInt("FFFF",16)-Integer.parseInt(x,16);

                        x = String.valueOf(x1*3.9);

                        ZhendongX zhendongX = new ZhendongX();

                        zhendongX.setCreateTime(dataInfo.getCreateTime());
                        zhendongX.setShebeiId(dataInfo.getShebeiId());
                        zhendongX.setStatus(0);
                        zhendongX.setX(x);

                        zhenDongXDao.save(zhendongX);
                    }
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }


            dataInfo.setStatus(5);

            dataInfoDao.save(dataInfo);
        }
    }


    /**
     * 获取y
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void checkY() {

        //查询数据信息
        List<DataInfo> dataInfoList = dataInfoDao.findByStatus(5);

        for (DataInfo dataInfo : dataInfoList) {
            try {
                if("A1".equals(dataInfo.getZhenTou()))
                {

                    String s1 = dataInfo.getDataString();

                    String start = s1.substring(138,140);

                    if(start.startsWith("0")||start.startsWith("A"))
                    {
                        String y = s1.substring(138,140) + s1.substring(136,138);

                        Integer y1 = Integer.parseInt(y,16);

                        y = String.valueOf(y1*3.9);

                        ZhendongY zhendongY = new ZhendongY();

                        zhendongY.setCreateTime(dataInfo.getCreateTime());
                        zhendongY.setShebeiId(dataInfo.getShebeiId());
                        zhendongY.setStatus(0);
                        zhendongY.setY(y);

                        zhenDongYDao.save(zhendongY);
                    }
                    else
                    {
                        String y = s1.substring(138,140) + s1.substring(136,138);

                        Integer y1 = Integer.parseInt("FFFF",16)-Integer.parseInt(y,16);

//                        Integer y1 = Integer.parseInt(y,16);

                        y = String.valueOf(y1*3.9);

                        ZhendongY zhendongY = new ZhendongY();

                        zhendongY.setCreateTime(dataInfo.getCreateTime());
                        zhendongY.setShebeiId(dataInfo.getShebeiId());
                        zhendongY.setStatus(0);
                        zhendongY.setY(y);

                        zhenDongYDao.save(zhendongY);
                    }
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }


            dataInfo.setStatus(6);

            dataInfoDao.save(dataInfo);
        }
    }


    /**
     * 获取z
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void checkZ() {

        //查询数据信息
        List<DataInfo> dataInfoList = dataInfoDao.findByStatus(6);

        for (DataInfo dataInfo : dataInfoList) {
            try {
                if("A1".equals(dataInfo.getZhenTou()))
                {

                    String s1 = dataInfo.getDataString();

                    String start = s1.substring(142,144);

                    if(start.startsWith("0")||start.startsWith("A"))
                    {
                        String z = s1.substring(142,144) + s1.substring(140,142);

                        Integer z1 = Integer.parseInt(z,16);

                        z = String.valueOf(z1*3.9);


                        ZhendongZ zhendongZ = new ZhendongZ();

                        zhendongZ.setCreateTime(dataInfo.getCreateTime());
                        zhendongZ.setShebeiId(dataInfo.getShebeiId());
                        zhendongZ.setStatus(0);
                        zhendongZ.setZ(z);

                        zhenDongZDao.save(zhendongZ);
                    }
                    else
                    {
                        String z = s1.substring(142,144) + s1.substring(140,142);

                        Integer z1 = Integer.parseInt("FFFF",16)-Integer.parseInt(z,16);

                        z = String.valueOf(z1*3.9);


                        ZhendongZ zhendongZ = new ZhendongZ();

                        zhendongZ.setCreateTime(dataInfo.getCreateTime());
                        zhendongZ.setShebeiId(dataInfo.getShebeiId());
                        zhendongZ.setStatus(0);
                        zhendongZ.setZ(z);

                        zhenDongZDao.save(zhendongZ);
                    }
                    //        z = z.substring(0,z.lastIndexOf(".")+3);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }


            dataInfo.setStatus(7);

            dataInfoDao.save(dataInfo);
        }
    }



    /**
     * 液位
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void checkYewei() {

        //查询数据信息
        List<DataInfo> dataInfoList = dataInfoDao.findByStatus(7);

        for (DataInfo dataInfo : dataInfoList) {
            try {
                if("A1".equals(dataInfo.getZhenTou()))
                {

                    String s1 = dataInfo.getDataString();

                    String gongneng03 = s1.substring(156,168);

                    String yewei = gongneng03.substring(8,12);

                    Integer yewei1 = Integer.parseInt(yewei,16);

                    Youliang oil = new Youliang();

                    oil.setCreateTime(dataInfo.getCreateTime());
                    oil.setShebeiId(dataInfo.getShebeiId());
                    oil.setStatus(0);
                    oil.setOil(String.valueOf(yewei1));

                    youliangDao.save(oil);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }


            dataInfo.setStatus(8);

            dataInfoDao.save(dataInfo);
        }
    }
}

